#include "../include/mytools.h"
 


bool parseopt(int argc, char *argv[], Popt opt, struct option *long_options, char * shortopts, bool fserver)
{
	int optc;
	while (1)
	{
		int this_option_optind = optind ? optind : 1;
		int option_index = 0;
		

		optc = getopt_long(argc, argv, shortopts,
						long_options, &option_index);
		if (optc == -1)
			break;
		if(fserver)
		{
			switch (optc)
			{
			case 0:
				printf("option %s", long_options[option_index].name);
				if (optarg)
					printf(" with arg %s", optarg);
				printf("\n");
				return false;
				break;
			case 'l':
				strcpy(opt->ip, optarg);
				break;

			case 'H':
				opt->hidden = true;
				break;

			case 'p':
				opt->port = atoi(optarg);
				break;

			case 'h':
				printf("Usage: fserver [OPTION] ... <DIR>\n\
serve some files over tcp\n\
\n\
args:\n\
    <DIR> Which directory to serve\n\
\n\
options:\n\
    -l, --listen=ADDR       specify source address to use [default is localhost]\n\
    -H, --hidden             show hidden file\n\
    -p, --port=PORT         specify listening port [default port is 12345]\n\
    -h, --help                display this help and exit\n");
				return false;
				break;

			case '?':
			default:
				printf("?? getopt returned character code 0%o ??\n", optc);
                return false;
			}
		}
		else
		{
			switch (optc)
			{
			case 0:
				printf("option %s", long_options[option_index].name);
				if (optarg)
					printf(" with arg %s", optarg);
				printf("\n");
				return false;
				break;
			case 'l':
				opt->show = true;
				break;

			case 's':
				strcpy(opt->ip, optarg);
				break;

			case 'p':
				opt->port = atoi(optarg);
				break;
			
			case 'd':
				strcpy(opt->sourcename, optarg);
				break;

			case 'o':
				strcpy(opt->outfilename, optarg);
				break;

			case 'h':
				printf("Usage: fclient [OPTION] ...\
download file from fserver over tcp \n\
options:\n\
    -l, --list                 show remote served files [default action]\n\
    -s, --server            specify server address [default addr is localhost]\n\
    -p, --port                 specify server port [default port is 12345]\n\
    -d, --dl=FILE              download specified file\n\
    -o, --output=FILE        output to the FILE\n\
    -h, --help                display this help and exit\n");
				return false;
				break;

			case '?':
			default:
				printf("?? getopt returned character code 0%o ??\n", optc);
                return false;
			}
		}
	}

	if (optind < argc-1)
	{
		printf("non-option ARGV-elements: ");
		while (optind < argc)
			printf("%s ", argv[optind++]);
		printf("\n");
	}
	if(opt->port > MAX_PORT_NUM)
	{
		printf("this port: %d is invaild.\n", opt->port);
		return false;
	}
	if(!is_ipv4_addr(opt->ip))
	{
		printf("failed to start fserver: %s is not a valid address\n", opt->ip);
		return false;
	}
    return true;
}

